package com.exam.base.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * 辅助工具
 * @author Administrator
 *
 */
public class DaoHelperUtil {
	private DaoHelperUtil(){
		
	}
	
	/**
	 * 反射类
	 * @param clazz
	 * @param index
	 * @return
	 */ 
	@SuppressWarnings("rawtypes")
	public static Class getClassGenricType(Class clazz, int index) {
		Type genType = clazz.getGenericSuperclass();
		if (!(genType instanceof ParameterizedType)) {
			return  Object.class;
		}
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		if ((index >= params.length) || (index < 0)) {
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			return  Object.class;
		}
		return (Class) params[index];
	}
	
	/**
	 * 去除重复数据
	 * @param ids
	 * @return List<T>
	 */
	public static <T> List<T> removeDuplicate(List<T> ids)
	{
		List<T> idsNew = new ArrayList<T>();
		LinkedHashSet<T> h = new LinkedHashSet<T>(ids);
		idsNew.addAll(h);
		return idsNew;
	}

	/**
	 * 按照指定size 拆分list
	 * @param <T>
	 * @param list
	 * @param pagesize
	 * @return Map<String, List<String>>
	 */
	public static <T> Map<String, List<T>> splitList(List<T> list, int pagesize)
	{
		Map<String, List<T>> mapList = new LinkedHashMap<String, List<T>>();
		if (pagesize == 0)
		{
			return mapList;
		}
		int totalcount = list.size();
		int pagecount = 0;
		int m = totalcount % pagesize;
		if (m > 0)
		{
			pagecount = totalcount / pagesize + 1;
		}
		else
		{
			pagecount = totalcount / pagesize;
		}

		for (int i = 1; i <= pagecount; i++)
		{
			List<T> subList = null;
			if (m == 0)
			{
				subList = list.subList((i - 1) * pagesize, pagesize * (i));
			}
			else
			{

				if (i == pagecount)
				{
					subList = list.subList((i - 1) * pagesize, totalcount);
				}
				else
				{
					subList = list.subList((i - 1) * pagesize, pagesize * (i));
				}
			}
			mapList.put(String.valueOf(i), subList);
		}
		return mapList;

	}
}
